import _ from 'lodash-es'
import type { DictDataType, DictParams } from '../types'

interface ObserverOption {
  loading: boolean
  callbacks: Fn[]
}

function getParamsKey(params: DictParams) {
  return `${params.dictType}`
}

export class Observer {
  cacheDict: { [key: string]: DictDataType[] } = {}
  cacheDictOpt: { [key: string]: ObserverOption | undefined } = {}

  constructor() {}

  getCache(params: DictParams = {}, callback?: Fn) {
    const key = getParamsKey(params)
    const val = this.cacheDict[key]
    const opt = this.cacheDictOpt[key]
    if (!val && !opt) {
      this.cacheDictOpt[key] = { loading: true, callbacks: [] }
      callback && this.cacheDictOpt[key].callbacks.push(callback)

      // 执行请求
      // getData(params).then((res) => {
      //   this.setCache(res)
      // })
    } else if (!val && opt?.loading) {
      callback && this.cacheDictOpt[key]?.callbacks.push(callback)
    } else {
      callback && callback(_.cloneDeep(val) || [])
    }
  }

  setCache(params: DictParams = {}, data: DictDataType[] = []) {
    const key = getParamsKey(params)
    this.cacheDict[key] = data
    if (this.cacheDictOpt[key]) {
      this.cacheDictOpt[key].loading = false
      this.cacheDictOpt[key].callbacks.forEach(fn => fn(_.cloneDeep(data)))
      this.cacheDictOpt[key].callbacks = []
    }
  }

  async requestCache(params: DictParams = {}) {
    const key = getParamsKey(params)
    const val = this.cacheDict[key]
    if (!val) {
      // 请求数据
      // const res = await getDictData(params)
      // this.cacheDict[key] = res
    }

    return _.cloneDeep(val) || []
  }
}
